﻿using GCC.Container.Abstracts;

namespace TTGIS.TileServer.API
{
    internal class FileCache
    {
        private readonly string _rootFolder;

        private readonly byte[] _404Image = new byte[0];

        public static FileCache? Instance { get => _instance; }
        private static FileCache? _instance;
        private static readonly string _instanceLock = Guid.NewGuid().ToString("N");
        private FileCache(string rootFolder)
        {
            _rootFolder = rootFolder;
            if (File.Exists(Path.Combine(rootFolder, "404.png")))
            {
                using FileStream notFoundImage = File.OpenRead(Path.Combine(rootFolder, "404.png"));
                _404Image = new byte[notFoundImage.Length];
                _ = notFoundImage.Read(_404Image);
            }
        }
        public static FileCache Init(AbsGCCContext context)
        {
            if (_instance is null)
            {
                lock (_instanceLock)
                {
                    if (_instance is null)
                    {
                        var tileAddress = context.GetConfigByPath(new string[] { context.PointName ?? "", "TileAddress" });
                        _instance = new FileCache(tileAddress);
                    }
                }
            }
            return _instance;
        }
        private string GetPath(int type, long x, long y, int zoom)
        {
            return Path.Combine(_rootFolder, $"{type}", $"{zoom}", $"{x}", $"{y}.png");
        }

        public byte[] GetImageBytes(int type, long x, long y, int zoom)
        {
            FileInfo fileInfo = new(GetPath(type, x, y, zoom));
            if (fileInfo.Exists)
            {
                using FileStream fs = fileInfo.OpenRead();
                byte[] bytes = new byte[fs.Length];
                _ = fs.Read(bytes);
                return bytes;
            }
            return _404Image;
        }
    }

}
